package com.s64.service;

import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.s64.entity.Book;
import com.s64.entity.Order;
import com.s64.mapper.OrderMapper;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    @Autowired
    private BookService bookService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Transactional
    @Override
    public boolean createOrder(Long bookId, Integer userId) {
        // 0. 检查库存
        /*if (book.getAmount() <= 0) {
            System.out.println("商品已经秒完，生成订单失败");
            return false;
        }*/
        DefaultRedisScript<String> redisScript = new DefaultRedisScript();
        // 设置lua脚本
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("stock_simple.lua")));
        redisScript.setResultType(String.class);
        List<String> keys = new ArrayList<>();
        keys.add(BookServiceImpl.BOOK_KEY);
        StringRedisSerializer serializer = new StringRedisSerializer();
        // 执行lua脚本
        String res = stringRedisTemplate.execute(redisScript,serializer,serializer,keys, bookId.toString());
        if(!"1".equals(res)){
            System.out.println("商品已经秒完，生成订单失败");
            return false;
        }
        Book book = bookService.getById(bookId);
        Order order = new Order();
        order.setBookId(bookId);
        order.setCreateTime(new Date());
        order.setOrderId(new DefaultIdentifierGenerator().nextId(null).toString());
        order.setStatus(0);
        order.setUserId(userId);
        BigDecimal price = book.getPrice();
        price = price.multiply(new BigDecimal("0.5"));
        order.setMoney(price);
        // 使用mq发送消息
        rabbitTemplate.convertAndSend("direct", "order.created", order);
        return true;
    }

}
